<template>
    <view class="pb-180">
        <image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
            mode="aspectFill">
        </image>
        <u-navbar :title="view ? '土壤检测单详情' : '编辑检测单'" :autoBack="true" leftIconColor="#fff" bgColor="transparent" :titleStyle="{ color: '#fff' }"
            safeAreaInsetTop placeholder></u-navbar>
        
        <!-- 基本信息 -->
        <view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20">
            <view class="fs-28 fw-b">基本信息</view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>检测编号</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.inspectionCode" :disabled="view" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>抽样编号</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.simplingCode" :disabled="view" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>抽样单ID</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.samplingId" :disabled="view" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>监测年份</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.monitorYear" :disabled="view" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>监测类型</view>
                <input class="trt fs-28" placeholder="请输入" v-model="monitorTypeText" :disabled="true" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>任务级别</view>
                <input class="trt fs-28" placeholder="请输入" v-model="levelText" :disabled="true" />
            </view>
        </view>
        
        <!-- 封样信息 -->
        <view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20">
            <view class="fs-28 fw-b">封样信息</view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>封样人员</view>
                <input class="trt fs-28" placeholder="多个人员用逗号隔开" v-model="formData.sealedSamplePerson" :disabled="view" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>封样状态</view>
                <view class="trt fs-28">
                    <picker v-if="!view" :value="sealedStatusIndex" :range="sealedStatusOptions" @change="onSealedStatusChange">
                        <view class="picker-text">{{ sealedStatusText }}</view>
                    </picker>
                    <view v-else>{{ sealedStatusText }}</view>
                </view>
            </view>
        </view>
        
        <!-- 检测结果 -->
        <view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20">
            <view class="fs-28 fw-b">检测结果</view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>检测类型</view>
                <view class="trt fs-28">
                    <picker v-if="!view" :value="detectionTypeIndex" :range="detectionTypeTextOptions" @change="onDetectionTypeChange">
                        <view class="picker-text">{{ detectionTypeText }}</view>
                    </picker>
                    <view v-else>{{ detectionTypeText }}</view>
                </view>
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>检测结果</view>
                <view class="trt fs-28">
                    <picker v-if="!view" :value="inspectionResultIndex" :range="inspectionResultOptions" @change="onInspectionResultChange">
                        <view class="picker-text">{{ inspectionResultText }}</view>
                    </picker>
                    <view v-else>{{ inspectionResultText }}</view>
                </view>
            </view>
        </view>
        
        <!-- 检测项目明细 -->
        <view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20" v-if="formData.sylSoilMonitorSamplingInspectionSheetExtList && formData.sylSoilMonitorSamplingInspectionSheetExtList.length > 0">
            <view class="fs-28 fw-b">检测项目明细</view>
            <view class="inspection-detail-table">
                <view class="table-header">
                    <view class="table-cell">检测项目</view>
                    <view class="table-cell">检测标准</view>
                    <view class="table-cell">检测方法</view>
                    <view class="table-cell">限量值</view>
                    <view class="table-cell">实测值</view>
                    <view class="table-cell">结论</view>
                </view>
                <view class="table-row" v-for="(item, index) in formData.sylSoilMonitorSamplingInspectionSheetExtList" :key="index">
                    <view class="table-cell">{{ item.testItem || '-' }}</view>
                    <view class="table-cell">{{ item.testStandard || '-' }}</view>
                    <view class="table-cell">{{ item.testMethod || '-' }}</view>
                    <view class="table-cell">{{ getLimitValue(item) }}</view>
                    <view class="table-cell">
                        <input v-if="!view" class="table-input" v-model="item.actualNum" placeholder="请输入实测值" />
                        <text v-else>{{ item.actualNum || '-' }}</text>
                    </view>
                    <view class="table-cell">
                        <picker v-if="!view" :value="getResultIndex(item.result)" :range="resultOptions" @change="onResultChange($event, index)">
                            <view class="picker-text">{{ item.result || '请选择' }}</view>
                        </picker>
                        <text v-else>{{ item.result || '-' }}</text>
                    </view>
                </view>
            </view>
        </view>
        
        <!-- 其他信息 -->
        <view class="w-710 mgt bgff pl-32 pr-32 br-20 pt-20">
            <view class="fs-28 fw-b">其他信息</view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view class="colfff bg rowsc rowsm w-180 h-60 br-12">上传附件</view>
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view class="w-132">备注</view>
                <textarea class="trt fs-28" placeholder="请输入备注" v-model="formData.remarks" :disabled="view" style="height: 120rpx; padding: 20rpx 0;"></textarea>
            </view>
        </view>
        
        <!-- 操作按钮 -->
        <view v-if="!view" class="fixed-bottom">
            <view @tap="save()" class="w-300 h-88 br-50 rowsc rowsm fs-36 colfff bg">
                保存
            </view>
        </view>
    </view>
</template>

<script>
import { inspectionItem, updateInspectionSheet, typeSoil, levelSoil } from '@/api/soiljcd'
export default {
    data() {
        return {
            id: '',
            view: false,
            edit: false,
            formData: {
                id: null,
                samplingId: null,
                simplingCode: '',
                monitorYear: null,
                monitorType: '',
                level: '',
                inspectionCode: '',
                sealedSamplePerson: '',
                sealedSampleStatus: '',
                selectRiskNum: '',
                inspectionResult: '',
                attachment: '',
                remarks: '',
                createTime: '',
                updateTime: '',
                sylSoilMonitorSamplingInspectionSheetExtList: []
            },
            // 字典数据
            typeOptions: [],
            levelOptions: [],
            detectionTypeOptions: [],
            // 选择器选项
            sealedStatusOptions: ['未封样', '已封样'],
            inspectionResultOptions: ['待检测', '合格', '不合格'],
            resultOptions: ['合格', '不合格']
        }
    },
    onLoad(options) {
        this.id = options.id
        this.view = options.view === 'true'
        this.edit = options.edit === 'true'
        this.inspectionItem()
        this.loadDictData()
    },
    methods: {
        inspectionItem() {
            inspectionItem(this.id).then(res => {
                console.log(res)
                this.formData = res.data
            })
        },
        // 加载字典数据
        loadDictData() {
            // 加载监测类型
            typeSoil().then(res => {
                this.typeOptions = res.data.map(item => ({
                    value: item.dictValue,
                    text: item.dictLabel
                }))
            })
            // 加载任务级别
            levelSoil().then(res => {
                this.levelOptions = res.data.map(item => ({
                    value: item.dictValue,
                    text: item.dictLabel
                }))
            })
            // 检测类型选项（风险筛选值）
            this.detectionTypeOptions = [
                { value: 'le55', text: 'pH≤5.5' },
                { value: '_55to65', text: '5.5<pH≤6.5' },
                { value: '_65to75', text: '6.5<pH≤7.5' },
                { value: 'g75', text: 'pH>7.5' }
            ]
        },
        // 封样状态选择
        onSealedStatusChange(e) {
            const index = e.detail.value
            this.formData.sealedSampleStatus = index === '0' ? '0' : '1'
        },
        // 检测类型选择
        onDetectionTypeChange(e) {
            const index = e.detail.value
            this.formData.selectRiskNum = this.detectionTypeOptions[index].value
        },
        // 检测结果选择
        onInspectionResultChange(e) {
            const index = e.detail.value
            this.formData.inspectionResult = index === '0' ? '' : (index === '1' ? '1' : '2')
        },
        // 结论选择
        onResultChange(e, rowIndex) {
            const index = e.detail.value
            this.formData.sylSoilMonitorSamplingInspectionSheetExtList[rowIndex].result = this.resultOptions[index]
        },
        // 获取结论索引
        getResultIndex(result) {
            return this.resultOptions.indexOf(result || '')
        },
        // 获取限量值
        getLimitValue(row) {
            if (!this.formData.selectRiskNum) {
                return '-'
            }
            if (!row.limitedEditionNum) {
                return '-'
            }
            try {
                const riskData = typeof row.limitedEditionNum === 'string'
                    ? JSON.parse(row.limitedEditionNum)
                    : row.limitedEditionNum
                switch (this.formData.selectRiskNum) {
                    case 'le55':
                        return riskData.le55 || '-'
                    case '_55to65':
                        return riskData._55to65 || '-'
                    case '_65to75':
                        return riskData._65to75 || '-'
                    case 'g75':
                        return riskData.g75 || '-'
                    default:
                        return '-'
                }
            } catch (error) {
                return '-'
            }
        },
        // 保存
        save() {
            if (!this.formData.selectRiskNum) {
                uni.showToast({
                    title: '请选择检测类型',
                    icon: 'none'
                })
                return
            }
            
            updateInspectionSheet(this.formData).then(res => {
                if (res.code === 200) {
                    uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                    })
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                } else {
                    uni.showToast({
                        title: res.msg || '保存失败',
                        icon: 'none'
                    })
                }
            }).catch(err => {
                console.error('保存失败:', err)
                uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                })
            })
        }
    },
    computed: {
        navbarHeight() {
            const systemInfo = uni.getSystemInfoSync();
            // 将px转换为rpx (1px = 2rpx)
            const statusBarHeightRpx = systemInfo.statusBarHeight * 2;
            const navbarHeightRpx = 44 * 2; // 44px = 88rpx
            return statusBarHeightRpx + navbarHeightRpx;
        },
        // 监测类型文字
        monitorTypeText() {
            if (!this.formData.monitorType) return '-'
            const option = this.typeOptions.find(item => item.value === this.formData.monitorType)
            return option ? option.text : this.formData.monitorType
        },
        // 任务级别文字
        levelText() {
            if (!this.formData.level) return '-'
            const option = this.levelOptions.find(item => item.value === this.formData.level)
            return option ? option.text : this.formData.level
        },
        // 封样状态文字
        sealedStatusText() {
            if (this.formData.sealedSampleStatus === '1') return '已封样'
            if (this.formData.sealedSampleStatus === '0') return '未封样'
            return '未封样'
        },
        // 封样状态索引
        sealedStatusIndex() {
            return this.formData.sealedSampleStatus === '1' ? 1 : 0
        },
        // 检测类型文字
        detectionTypeText() {
            if (!this.formData.selectRiskNum) return '请选择'
            const option = this.detectionTypeOptions.find(item => item.value === this.formData.selectRiskNum)
            return option ? option.text : this.formData.selectRiskNum
        },
        // 检测类型索引
        detectionTypeIndex() {
            return this.detectionTypeOptions.findIndex(item => item.value === this.formData.selectRiskNum)
        },
        // 检测结果文字
        inspectionResultText() {
            if (this.formData.inspectionResult === '1') return '合格'
            if (this.formData.inspectionResult === '2') return '不合格'
            return '待检测'
        },
        // 检测结果索引
        inspectionResultIndex() {
            if (this.formData.inspectionResult === '1') return 1
            if (this.formData.inspectionResult === '2') return 2
            return 0
        },
        // 检测类型文本选项
        detectionTypeTextOptions() {
            return this.detectionTypeOptions.map(item => item.text)
        }
    }
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 750rpx;
    z-index: 1;
}

.picker-text {
    color: #333;
    font-size: 28rpx;
}

.fixed-bottom {
    position: fixed;
    bottom: 68rpx;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    z-index: 10;
}

// 检测项目明细表格样式
.inspection-detail-table {
    margin-top: 20rpx;
    border: 2rpx solid #e4e7ed;
    border-radius: 8rpx;
    overflow: hidden;
}

.table-header {
    display: flex;
    background: #f5f7fa;
    font-weight: 600;
    color: #606266;
    font-size: 24rpx;
}

.table-row {
    display: flex;
    border-top: 2rpx solid #e4e7ed;
    min-height: 80rpx;
    align-items: center;
}

.table-cell {
    flex: 1;
    padding: 20rpx 16rpx;
    font-size: 24rpx;
    color: #606266;
    border-right: 2rpx solid #e4e7ed;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    word-break: break-all;
    
    &:last-child {
        border-right: none;
    }
}

.table-input {
    width: 100%;
    height: 60rpx;
    border: 2rpx solid #dcdfe6;
    border-radius: 4rpx;
    padding: 0 16rpx;
    font-size: 24rpx;
    text-align: center;
    
    &:focus {
        border-color: #409eff;
    }
}

// 响应式调整
@media screen and (max-width: 750rpx) {
    .table-cell {
        font-size: 20rpx;
        padding: 16rpx 8rpx;
    }
    
    .table-input {
        font-size: 20rpx;
        height: 50rpx;
    }
}
</style>